package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Slf4j
@Api(tags ="通用接口")
@RestController("adminCommonController")
@RequestMapping("/admin/common")
public class CommonController {

    //配置类的作用
    @Autowired
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @ApiOperation("文件上传接口")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) {
        //2.获取文件名称
        String originalFilename = file.getOriginalFilename(); // 获取文件原始名称
        log.info("文件上传, 原始文件名: {}", originalFilename);
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")); // 获取文件后缀名称: .jpg
        String url = null;
        try {
            //1.调用AliOsUtil工具类的upload文件上传方法
            //第一参数是上传的文件, 存储到Oss的文件名, 也是返回路径的名字
            String objectName = UUID.randomUUID().toString() + suffix; //随机生成
            url = aliOssUtil.upload(file.getBytes(), objectName);
        } catch (Exception e) {
            log.info("文件上传失败:{}", e.getMessage());
            return Result.error("文件上传失败!");
        }
        //3.返回路径
        return Result.success(url);

    }
}
